// This program is copyright VUW.
// You are granted permission to use it to construct your answer to a XMUT103 assignment.
// You may not distribute it in any other way without permission.

/* Code for XMUT103 - 2022T1, Assignment 2
 * Name:
 * Username:
 * ID:
 */

import ecs100.*;

import java.util.Stack;

/** Pencil   */
public class Pencil_1{
    private double lastX;
    private double lastY;

    class Point {
        private double x;
        private double y;

        boolean isPressed;

        public Point(double x, double y, boolean isPressed) {
            this.x = x;
            this.y = y;
            this.isPressed = isPressed;
        }
    }

    private Stack<Point> pointStack = new Stack<>();

    /**
     * Setup the GUI
     */
    public void setupGUI(){
        UI.setMouseMotionListener(this::doMouse);
        UI.addButton("Quit", UI::quit);
        UI.addButton("Undo", ()->{
           if (pointStack.isEmpty())    return;
            Point lastPoint = pointStack.pop();
            while (!lastPoint.isPressed){
                Point temp = pointStack.pop();
                UI.eraseLine(lastPoint.x, lastPoint.y, temp.x, temp.y);
                lastPoint = temp;
            }
        });
        UI.setLineWidth(3);
        UI.setDivider(0.0);
    }

    /**
     * Respond to mouse events
     */
    public void doMouse(String action, double x, double y) {
        if (action.equals("pressed")){
            lastX = x;
            lastY = y;
            pointStack.push(new Point(x, y, true));
        }
        else if (action.equals("dragged")){
            UI.drawLine(lastX, lastY, x, y);
            lastX = x;
            lastY = y;
            pointStack.push(new Point(x, y, false));
        }
        else if (action.equals("released")){
            UI.drawLine(lastX, lastY, x, y);
            pointStack.push(new Point(x, y, false));
        }
    }

    public static void main(String[] arguments){
        new Pencil_1().setupGUI();
    }

}
